<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { useSendInviteCodeService } from '../services'
  import { ElMessage, FormInstance, FormItemProp } from 'element-plus'
  import { HButton, HLink, HModal, HPlainButton } from '@/components/common'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: () => false,
    },
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
  }>()

  // 使用服务
  const { loading, send } = useSendInviteCodeService()

  /**
   * 表单
   */
  const form = ref({
    phone1: '',
  })

  // 弹窗显示状态
  const visible = ref(false)

  // 关闭事件
  const onClose = () => {
    visible.value = false
    const keys = Object.keys(form.value)
    keys.forEach((key) => {
      form.value[key] = ''
    })
    emits('update:modelValue', visible.value)
  }

  /**
   * 表达那验证规则
   */
  const rules = ref({
    phone1: [{ required: true, message: '请输入手机号码', trigger: ['blur', 'change'] }],
  })

  // 添加手机号事件
  const addPhone = async () => {
    if (formRef.value) {
      try {
        await formRef.value.validate()
        const keys = Object.keys(form.value)
        form.value[`phone${keys.length + 1}`] = ''
        rules.value[`phone${keys.length + 1}`] = [
          { required: true, message: '请输入手机号码', trigger: ['blur', 'change'] },
        ]
      } catch (error) {
        // error
      }
    }
  }

  // 移除手机号事件
  const handleRemovePhone = (key: string) => {
    delete form.value[key]
    delete rules.value[key]
  }

  /**
   * 表单验证结果
   */
  const formValidateResult = ref<Record<string, boolean>>({})

  /**
   * 表单组件实例
   */
  const formRef = ref<FormInstance | null>(null)

  // 发送事件
  const onSend = async () => {
    if (formRef.value) {
      try {
        await formRef.value.validate()
        const res = await send(Object.values(form.value))
        onClose()
        ElMessage({
          type: res.code === 20000 ? 'success' : 'error',
          message: res.message,
        })
        form.value = { phone1: '' }
      } catch (error) {
        // error
      }
    }
  }

  /**
   * 表单验证事件
   */
  const handleFormValidate = (prop: FormItemProp, isValid: boolean) => {
    formValidateResult.value[prop as string] = isValid
  }

  watch(props, (value) => {
    visible.value = value.modelValue
  })
</script>

<template>
  <div>
    <HModal v-model="visible" @close="onClose" title="发送短信" :width="500">
      <el-form
        ref="formRef"
        v-loading="loading"
        label-width="90"
        :rules="rules"
        :model="form"
        @validate="handleFormValidate"
        class="form_content"
      >
        <el-form-item>
          <template #label>
            <span style="opacity: 0">占位不做显示</span>
          </template>
          <HPlainButton :height="22" :padding-lr="6" @click="addPhone"> 添加手机号 </HPlainButton>
        </el-form-item>

        <div class="phone_form_item_list">
          <template v-for="(item, index) in Object.keys(form)" :key="index">
            <el-form-item
              required
              :label="`手机号码${index + 1}`"
              :prop="item"
              :class="{
                form_item: formValidateResult[item] && index !== Object.keys(form).length - 1,
                validate_fail: !formValidateResult[item] && index !== Object.keys(form).length - 1,
              }"
            >
              <div class="phone_input_container">
                <el-input
                  :maxlength="11"
                  placeholder="请输入手机号码"
                  v-model="form[item]"
                  @input="form[item] = form[item].replace(/[^0-9]/g, '')"
                />

                <div class="operate">
                  <HLink
                    v-if="Object.keys(form).length >= 2"
                    @click="handleRemovePhone(item)"
                    type="error"
                  >
                    删除
                  </HLink>
                </div>
              </div>
            </el-form-item>
          </template>
        </div>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onSend">发送</HButton>
        <HButton is-modal @click="onClose">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  .phone_input_container {
    width: 100%;
    display: flex;
    gap: 5px;

    .operate {
      width: 24px;
    }
  }

  .error_tip {
    color: $deleteColor;
    font-size: 12px;
    transition: all 0.4s;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }

  .form_content {
    .form_item {
      margin-bottom: 12px;
      transition: all 0.4s;
    }

    .validate_fail {
      margin-bottom: 22px;
      transition: all 0.4s;
    }

    .phone_form_item_list {
      height: 200px;
      overflow: auto;
    }
  }
</style>
